import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import SignatureCanvas from 'react-signature-canvas';
import ResizeObserver from 'resize-observer-polyfill';
import { Button, Col, Row } from 'antd';
import styles from './index.css';

class Signature extends PureComponent {
  static propTypes = {
    submitSign: PropTypes.func.isRequired, // 提交签名图片
  };

  constructor(props) {
    super(props);
    this.state = {
      cvWidth: null,
    };
  }

  reset = () => {
    this.canvas.clear();
  }

  parentRef = (cw) => { // containerWrap
    if (cw) {
      const ro = new ResizeObserver((entries, observer) => {
        // eslint-disable-next-line no-restricted-syntax
        for (const entry of entries) {
          const { left, top, width, height } = entry.contentRect;
          this.setState({
            cvWidth: width,
          });
        }
      });
      ro.observe(cw);
    }
  };

  save = () => {
    const { submitSign } = this.props;
    const imgUrl = this.canvas.toDataURL('image/png');
    submitSign(imgUrl);
  }

  render() {
    const { cvWidth } = this.state;
    const canvasProps = {
      width: cvWidth || '500px',
      height: '100%',
      className: 'sigCanvas',
      style: {
        backgroundColor: 'white',
      },
    };
    return (
      <React.Fragment>
        <h2><div className={styles.div_title}>Digital Signature 电子签名</div></h2>

        <div className={styles.div_description}>
          Use the box below to enter your signature. If you’re using a
          touchscreen, you can sign directly. Otherwise, use the mouse on your computer.
          请在以下方框内签名，触屏设备可直接手签，电脑设备可用鼠标签字
        </div>
        <div className={styles.div_signature} ref={this.parentRef}>
          <SignatureCanvas penColor="black"
                           canvasProps={canvasProps}
                           ref={(ref) => {
                             this.canvas = ref;
                           }}
          />
        </div>
        <Row type="flex" justify="center">
          <Col>
            <Button onClick={this.reset}>Re-Sign(重新签名)</Button>
          </Col>
          <Col span={1} />
          <Button type="primary" onClick={this.save}>Submit(提交)</Button>
        </Row>
      </React.Fragment>
    );
  }
}

export default Signature;
